package utils

import (
	"crypto/rand"
	"fmt"
	"gin_web/config"
	"github.com/golang-jwt/jwt/v5"
	"time"
)

var JWT_KEY []byte

const TokenType = "bearer"

type JwtClaims struct {
	Username  string `json:"username"`
	TokenType string `json:"tokenType"`
	jwt.RegisteredClaims
}

type TokenData struct {
	TokenType string `json:"tokenType"`
	ExpiresIn int64  `json:"expiresIn"`
	Token     string `json:"token"`
}

func NewTokenData(token string) *TokenData {
	return &TokenData{
		TokenType: TokenType,
		ExpiresIn: config.GConfig.Jwt.ExpTime,
		Token:     token,
	}
}

func init() {
	JWT_KEY = make([]byte, 32) // 生成32字节（256位）的密钥
	if _, err := rand.Read(JWT_KEY); err != nil {
		panic(err)
	}
}

func GenerateJWT(username string) (string, error) {
	jwtConfig := config.GConfig.Jwt
	expTime := time.Now().Add(time.Duration(jwtConfig.ExpTime) * time.Second)
	c := JwtClaims{
		Username:  username,
		TokenType: TokenType,
		RegisteredClaims: jwt.RegisteredClaims{
			NotBefore: jwt.NewNumericDate(time.Now()), // 生效时间
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			ExpiresAt: jwt.NewNumericDate(expTime),
			Issuer:    jwtConfig.Issuer,
		},
	}
	t := jwt.NewWithClaims(jwt.SigningMethodHS256, c)

	s, err := t.SignedString([]byte(jwtConfig.Secret))
	return s, err
}

func ParseJwt(jwtString string) (*JwtClaims, error) {
	token, err := jwt.ParseWithClaims(jwtString, &JwtClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(config.GConfig.Jwt.Secret), nil
	})
	if err != nil {
		return nil, err
	}
	fmt.Println(token.Claims)
	if claims, ok := token.Claims.(*JwtClaims); ok && token.Valid {
		return claims, nil
	} else {
		return nil, err
	}
}
